<template>
  <div class="data-collection">
    <!-- 上部分：状态栏 -->
    <div class="status-bar">
      <div class="status-left">
        <span class="time">{{ currentTime }}</span>
        <el-divider direction="vertical" />
        <span class="status">
          <el-tag
            :type="collectionStatus === '采集中' ? 'success' : 'info'"
            size="small"
          >
            {{ collectionStatus }}
          </el-tag>
        </span>
        <el-divider direction="vertical" />
        <span class="countdown">{{ collectionDuration }}</span>
        <el-button
          type="danger"
          size="small"
          @click="stopCollection"
          :disabled="collectionStatus === '待机'"
        >
          停止
        </el-button>
      </div>
      <div class="status-right">
        <el-button
          type="primary"
          @click="toggleCollection"
          :disabled="collectionStatus === '采集中'"
        >
          采集
        </el-button>
      </div>
    </div>

    <!-- 工具栏：添加状态检测按钮 -->
    <div class="video-toolbar">
      <div class="toolbar-left">
        <el-button 
          size="small" 
          type="primary" 
          @click="loadVideoStreamList"
          :loading="isLoadingVideoList"
          :disabled="collectionStatus === '采集中'"
        >
          <el-icon><Refresh /></el-icon>
          {{ isLoadingVideoList ? '加载中...' : '刷新视频流' }}
        </el-button>

        <span style="margin-left: 10px; color: #666; font-size: 12px;">
          总数: {{ videoList.length }} | 
          已启用: {{ videoList.filter(v => v.isEnabled).length }} | 
          已停用: {{ videoList.filter(v => !v.isEnabled).length }} | 
          在线: {{ videoList.filter(v => v.isEnabled && v.status === 'online').length }} | 
          离线: {{ videoList.filter(v => v.isEnabled && v.status === 'offline').length }}
        </span>
      </div>
      <div class="toolbar-right">
        <span class="toolbar-label">窗口布局</span>
        <el-select
          v-model="windowLayout"
          size="small"
          style="width: 120px"
          @change="refreshGrid"
        >
          <el-option label="每行2路" value="2" />
          <el-option label="每行3路" value="3" />
          <el-option label="每行4路" value="4" />
        </el-select>
      </div>
    </div>

    <!-- 视频卡片区：高度固定，超出滚动 -->
    <div class="video-scroll-wrapper">
      <!-- 空状态显示 -->
      <div v-if="videoList.length === 0 && !isLoadingVideoList" class="empty-state">
        <el-empty description="暂无视频流数据">
          <el-button type="primary" @click="loadVideoStreamList">
            刷新视频流
          </el-button>
        </el-empty>
      </div>
      
      <!-- 加载状态显示 -->
      <div v-else-if="isLoadingVideoList" class="loading-state">
        <!-- <el-loading-component /> -->
        <p>正在加载视频流列表...</p>
      </div>
      
      <!-- 视频网格 -->
      <div v-else class="video-grid" :style="gridStyle">
        <div
          v-for="(item, i) in filteredVideoList"
          :key="item.id"
          class="video-card"
          :class="{ 'disabled': !item.isEnabled }"
        >
          <!-- 左上角title和状态 -->
          <div class="video-card-topbar">
            <span class="video-title">{{ item.name || item.title }}</span>
            <span
              class="video-status-text"
              :class="getStatusDisplay(item).class"
              :title="item.errorMessage || `最后检测: ${item.lastCheck ? new Date(item.lastCheck).toLocaleTimeString() : '未检测'}`"
            >
              {{ getStatusDisplay(item).text }}
            </span>
          </div>
          <!-- 右上角icon -->
          <div class="video-card-icons">
            <el-tooltip
              :content="item.collecting ? '取消采集' : '加入采集'"
              placement="top"
            >
              <el-icon
                class="video-icon"
                @click.stop="toggleCollect(i)"
                :class="{ 
                  disabled: collectionStatus === '采集中' || !item.isEnabled || item.status === 'offline',
                  collecting: item.collecting
                }"
              >
                <component :is="item.collecting ? UnlinkIcon : 'Link'" />
              </el-icon>
            </el-tooltip>

            <el-tooltip :content="getFullscreenTooltip(i)" placement="top">
              <el-icon 
                class="video-icon" 
                @click.stop="maximizeVideo(i)"
                :class="{ 
                  disabled: !item.isEnabled || item.status === 'offline',
                  fullscreen: isVideoFullscreen(i)
                }"
              >
                <ZoomOut v-if="isVideoFullscreen(i)" />
                <FullScreen v-else />
              </el-icon>
            </el-tooltip>

          </div>
          <div class="video-card-body">
            <RtspVideoPlayer
              v-if="item.isEnabled"
              :ref="(el) => (videoRefs.set(item.id, el))"
              :rtsp-url="item.src"
              :hide-controls="true"
              :show-controls="false"
              :autoplay="true"
              @error="handleVideoError"
              @connected="handleVideoConnected"
              @reconnectFailed="handleVideoReconnectFailed"
              @fullscreenChange="(isFullscreen) => handleFullscreenChange(isFullscreen, item.id)"
            />
            <div v-else class="video-placeholder disabled">
              <div class="disabled-content">
                <h4 class="disabled-title">已停用</h4>
                <p class="disabled-message">该视频流已被后台停用</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 下部分：遥测数据图表 -->
    <div class="chart-section">
      <TelemetryChart
        ref="telemetryChartRef"
        :is-collecting="collectionStatus === '采集中'"
      />
    </div>

    <!-- 采集完成确认弹窗 -->
    <el-dialog v-model="showConfirmDialog" title="采集完成确认" width="400px">
      <p>数据采集已完成，是否保存本次采集数据？</p>
      <div style="margin: 15px 0; padding: 10px; background: #f5f5f5; border-radius: 4px;">
        <p style="margin: 0; font-size: 14px; color: #666;">
          采集时长: {{ formatTime(actualCollectionDuration) }}<br>
          采集路数: {{ videoList.filter(v => v.collecting && v.isEnabled && v.status === 'online').length }} 路<br>
          数据路径: ./collections/{{ collectionTimestamp }}
        </p>
      </div>
      <template #footer>
        <el-button @click="cancelSave">取消</el-button>
        <el-button type="primary" @click="confirmSave">确认保存</el-button>
      </template>
    </el-dialog>

    <!-- 移除文件命名对话框 -->
    <!-- 
    <el-dialog
      v-model="showNamingDialog"
      title="视频文件命名"
      width="600px"
      :close-on-click-modal="false"
    >
      ...
    </el-dialog>
    -->
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from "vue";
import { ElMessage, ElLoading } from "element-plus";
import TelemetryChart from "./charts/TelemetryChart.vue";
import RtspVideoPlayer from "./RtspVideoPlayer.vue";
import { Link, FullScreen, Aim, Close, ZoomOut } from "@element-plus/icons-vue";
import UnlinkIcon from "./icons/UnlinkIcon.vue";

const currentTime = ref("");
const collectionStatus = ref("待机");
const collectionDuration = ref("00:00:00");
const collectionTimer = ref(null);
const collectionSeconds = ref(0);
const showConfirmDialog = ref(false);
const telemetryChartRef = ref();

// 新增：窗口布局
const windowLayout = ref(4); // 默认每行4路
const filterText = ref("");

// 视频列表 - 从视频流API获取
const videoList = ref([]);
const isLoadingVideoList = ref(false);

// WebSocket服务器配置
const wsServerUrl = ref("ws://localhost:8080");



// 加载视频流列表
// FFmpeg 状态检测
const checkFFmpegAvailability = async () => {
  try {
    const ffmpegStatus = await window.electronAPI.checkFFmpeg();
    console.log("FFmpeg 检测结果:", ffmpegStatus);
    
    if (!ffmpegStatus.available) {
      ElMessage.error(`FFmpeg 不可用: ${ffmpegStatus.message}`);
      return false;
    } else {
      console.log(`FFmpeg 可用: ${ffmpegStatus.version}`);
      return true;
    }
  } catch (error) {
    console.error("FFmpeg 检测失败:", error);
    ElMessage.error("无法检测 FFmpeg 状态");
    return false;
  }
};

const loadVideoStreamList = async () => {
  isLoadingVideoList.value = true;
  try {
    // 导入API模块
    const { videoStreamAPI } = await import('../api/index.js');
    
    // 获取所有视频流（不分页）
    const response = await videoStreamAPI.getVideoStreams({
      pageNum: 1,
      pageSize: 1000, // 获取所有数据
      orderByColumn: 'streamSort',
      isAsc: 'asc'
    });
    
    if (response && response.code == 0) {
      // 转换API数据为组件需要的格式
      const streams = response.rows || [];
      videoList.value = streams.map(stream => {
        // 调试状态值
        console.log(`视频流 ${stream.streamTitle} 的原始状态:`, stream.status, typeof stream.status);
        
        // 根据后台启用状态决定是否渲染视频组件
        let status = 'offline'; // 默认为离线状态，等待连接结果
        let collecting = false; // 默认不采集
        let isEnabled = true; // 是否启用（后台状态）
        
        if (stream.status === '0' || stream.status === 0) {
          isEnabled = true;
          collecting = true; // 启用的默认可以采集
        } else if (stream.status === '1' || stream.status === 1) {
          isEnabled = false;
          collecting = false; // 停用的不能采集
        } else {
          // 如果状态值不是预期的，默认为启用
          console.log(`未知状态值: ${stream.status}，默认为启用`);
          isEnabled = true;
          collecting = false;
        }
        
        return {
          id: stream.streamId,
          streamId: stream.streamId,
          src: stream.previewUrl || stream.captureUrl, // 优先使用预览链接
          streamUrl: stream.captureUrl || stream.previewUrl, // 采集使用采集链接
          status: status,
          isEnabled: isEnabled, // 是否启用
          collecting: collecting,
          name: stream.streamTitle,
          title: stream.streamTitle,
          type: 'network', // 默认为网络类型
          lastCheck: null,
          errorMessage: "",
          remark: stream.remark,
          streamSort: stream.streamSort
        };
      });
      
      console.log('加载视频流列表成功:', videoList.value);
      ElMessage.success(`成功加载 ${videoList.value.length} 个视频流`);
    } else {
      throw new Error(response?.msg || '获取视频流列表失败');
    }
  } catch (error) {
    console.error('加载视频流列表失败:', error);
    ElMessage.error('加载视频流列表失败，请检查网络连接');
    
    // 加载失败时清空列表
    videoList.value = [];
  } finally {
    isLoadingVideoList.value = false;
  }
};

const filteredVideoList = computed(() => {
  if (!filterText.value) return videoList.value;
  return videoList.value.filter((item) =>
    item.name.includes(filterText.value)
  );
});

const gridStyle = computed(() => {
  return {
    display: "grid",
    gridTemplateColumns: `repeat(${windowLayout.value}, 1fr)`,
    gap: "16px",
    minHeight: 0,
    padding: "0",
  };
});

// 使用Map来存储视频组件引用，避免索引不匹配问题
const videoRefs = ref(new Map());

// 添加全屏状态跟踪
const fullscreenStates = ref(new Map());

let timer = null;

// 更新当前时间 - 显示完整的年月日时分秒
const updateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  currentTime.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 格式化时间
const formatTime = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  return `${hours.toString().padStart(2, "0")}:${minutes
    .toString()
    .padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
};

// 开始采集计时
const startCollectionTimer = () => {
  collectionSeconds.value = 0;
  collectionTimer.value = setInterval(() => {
    collectionSeconds.value++;
    collectionDuration.value = formatTime(collectionSeconds.value);
  }, 1000);
};

// 停止采集计时
const stopCollectionTimer = () => {
  if (collectionTimer.value) {
    clearInterval(collectionTimer.value);
    collectionTimer.value = null;
  }
};







// 获取状态显示文本和样式
const getStatusDisplay = (video) => {
  // 根据后台启用状态和连接状态动态显示
  if (!video.isEnabled) {
    return { text: "已停用", class: "disabled" };
  } else if (video.errorMessage) {
    return { text: "离线", class: "offline" };
  } else if (video.status === "online") {
    return { text: "在线", class: "online" };
  } else {
    return { text: "离线", class: "offline" };
  }
};



// 保存视频源配置到接口
const saveVideoSourceConfig = async (video) => {
  try {
    // 导入API模块
    const { videoStreamAPI } = await import('../api/index.js');
    
    const result = await videoStreamAPI.updateVideoStream(video.streamId, {
      streamTitle: video.name,
      previewUrl: video.src,
      captureUrl: video.streamUrl,
      streamSort: video.streamSort || 1,
      status: video.collecting ? '0' : '1', // 0正常 1停用
      remark: video.type
    });
    
    if (result && result.code == 0) {
      ElMessage.success(`${video.name} 配置已保存`);
    } else {
      ElMessage.warning(`${video.name} 配置保存失败`);
    }
    

    
  } catch (error) {
    console.error("保存配置失败:", error);
    ElMessage.warning(`${video.name} 配置保存失败，使用本地缓存`);
    
    // 保存到本地缓存作为fallback
    const localConfig = JSON.parse(localStorage.getItem('videoSourcesConfig') || '{}');
    localConfig[video.streamId] = {
      name: video.name,
      streamUrl: video.streamUrl,
      enabled: video.collecting,
      type: video.type,
      lastUpdate: new Date().toISOString()
    };
    localStorage.setItem('videoSourcesConfig', JSON.stringify(localConfig));
  }
};

// 在 script setup 中添加视频采集相关的状态和方法
const collectionTimestamp = ref("");
const collectionProcesses = ref([]);
const isCollecting = ref(false);
const telemetryData = ref([]); // 用于存储遥测数据
const telemetryCollectionInterval = ref(null); // 遥测数据采集定时器

// 在 script setup 中添加采集时间跟踪
const actualCollectionStartTime = ref(null);
const actualCollectionEndTime = ref(null);
const actualCollectionDuration = ref(0);

// 格式化本地日期时间（北京时间）
const formatLocalDateTime = (date) => {
  const localDate = new Date(date);
  const year = localDate.getFullYear();
  const month = String(localDate.getMonth() + 1).padStart(2, '0');
  const day = String(localDate.getDate()).padStart(2, '0');
  const hours = String(localDate.getHours()).padStart(2, '0');
  const minutes = String(localDate.getMinutes()).padStart(2, '0');
  const seconds = String(localDate.getSeconds()).padStart(2, '0');
  const milliseconds = String(localDate.getMilliseconds()).padStart(3, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}:${milliseconds}`;
};

// 生成采集时间戳 - 简化为纯时间戳
const generateCollectionTimestamp = () => {
  const now = new Date();
  return (
    now.getFullYear().toString() +
    (now.getMonth() + 1).toString().padStart(2, "0") +
    now.getDate().toString().padStart(2, "0") +
    "_" +
    now.getHours().toString().padStart(2, "0") +
    now.getMinutes().toString().padStart(2, "0") +
    now.getSeconds().toString().padStart(2, "0")
  );
};

// 开始多路视频采集 - 只采集在线的视频源
const startVideoCollection = async () => {
  try {
    // 过滤逻辑：只采集在线且选择采集的视频源
    const collectingChannels = videoList.value.filter((v) => {
      return v.collecting && v.isEnabled && v.status === 'online';
    });
    
    console.log("=== 视频采集状态检查 ===");
    console.log("总视频数:", videoList.value.length);
    console.log("在线视频数:", videoList.value.filter(v => v.status === 'online').length);
    console.log("已选择采集的视频数:", videoList.value.filter(v => v.collecting).length);
    console.log("可采集的视频数:", collectingChannels.length);
    
    // 详细输出每个视频的状态
    videoList.value.forEach((video, index) => {
      console.log(`视频${index + 1}: ${video.name} - 状态:${video.status} - 采集:${video.collecting}`);
    });
    
    console.log("开始采集", collectingChannels.length, "路视频");

    if (collectingChannels.length === 0) {
      const enabledCount = videoList.value.filter(v => v.isEnabled).length;
      const onlineCount = videoList.value.filter(v => v.isEnabled && v.status === 'online').length;
      const collectingCount = videoList.value.filter(v => v.collecting).length;
      
      if (enabledCount === 0) {
        ElMessage.warning("没有启用的视频源，请联系管理员启用视频流");
      } else if (onlineCount === 0) {
        ElMessage.warning("没有在线的视频源，请检查视频流连接状态");
      } else if (collectingCount === 0) {
        ElMessage.warning("没有选择采集的视频源，请点击已启用的视频流上的采集按钮");
      } else {
        ElMessage.warning("没有可用的视频源，请检查视频源状态");
      }
      return;
    }

    collectionDuration.value = "准备中...";
    collectionTimestamp.value = generateCollectionTimestamp();

    const channelsData = collectingChannels.map((video) => ({
      id: video.id,
      name: video.name,
      streamUrl: video.streamUrl,
      type: video.type,
    }));

    console.log(`准备采集 ${channelsData.length} 路视频`);

    // 直接使用时间戳作为文件夹名
    const outputDir = `./collections/${collectionTimestamp.value}`;

    // 开始采集遥测数据
    startTelemetryDataCollection();
    
    const result = await window.electronAPI.startVideoCollection({
      channels: channelsData,
      outputDir: outputDir,
      maxDuration: 0, // 无时长限制
      startTime: new Date().toISOString(), // 使用当前时间
    });

    if (result.success) {
      isCollecting.value = true;
      collectionStatus.value = "采集中"; // 设置采集状态
      // 在FFmpeg成功启动后才设置实际开始时间，确保时间准确
      actualCollectionStartTime.value = new Date();
      startCollectionTimer(); // 启动计时器
      ElMessage.success(
        `开始采集 ${collectingChannels.length} 路视频，保存至: ${outputDir}`
      );
    } else {
      console.error("采集启动失败:", result.error);
      ElMessage.error(`采集启动失败: ${result.error || '未知错误'}`);
      collectionDuration.value = "00:00:00";
      collectionTimestamp.value = "";
      stopTelemetryDataCollection();
    }
  } catch (error) {
    console.error("启动视频采集失败:", error);
    ElMessage.error(`启动视频采集失败: ${error.message}`);
    collectionDuration.value = "00:00:00";
    collectionTimestamp.value = "";
    stopTelemetryDataCollection();
  }
};

// 开始采集遥测数据
const startTelemetryDataCollection = () => {
  // 清空之前的数据
  telemetryData.value = [];

  // 设置定时器，定期从遥测图表获取数据
  telemetryCollectionInterval.value = setInterval(() => {
    // 从遥测图表组件获取当前数据
    if (
      telemetryChartRef.value &&
      typeof telemetryChartRef.value.exportData === "function"
    ) {
      const currentData = telemetryChartRef.value.exportData();
      if (currentData && currentData.length > 0) {
        // 获取最新的数据点
        const latestPoint = currentData[currentData.length - 1];
        telemetryData.value.push({
          ...latestPoint,
          collectTime: new Date().toISOString(),
        });
      }
    }
  }, 1000); // 每秒采集一次数据
};

// 停止采集遥测数据并保存到本地JSON文件
const stopTelemetryDataCollection = async () => {
  // 停止数据采集
  if (telemetryCollectionInterval.value) {
    clearInterval(telemetryCollectionInterval.value);
    telemetryCollectionInterval.value = null;
  }

  // 保存遥测数据到本地
  if (collectionTimestamp.value && telemetryData.value.length > 0) {
    try {
      const telemetrySaveData = {
        collectionInfo: {
          timestamp: collectionTimestamp.value,
          startTime: actualCollectionStartTime.value
            ? actualCollectionStartTime.value.toISOString()
            : null,
          endTime: actualCollectionEndTime.value
            ? actualCollectionEndTime.value.toISOString()
            : null,
          duration: actualCollectionDuration.value,
          dataPointCount: telemetryData.value.length,
        },
        data: telemetryData.value,
      };

      // 直接保存到本地
      const outputDir = `./collections/${collectionTimestamp.value}`;
      const serializableData = JSON.parse(JSON.stringify(telemetrySaveData));

      // 通过electron API保存遥测数据
      const result = await window.electronAPI.saveTelemetryData({
        outputDir: outputDir,
        fileName: "telemetry_data.json",
        data: serializableData,
      });

      if (result.success) {
        ElMessage.success(`遥测数据已保存到本地: ${result.filePath}`);
      } else {
        ElMessage.error(`遥测数据保存失败: ${result.error}`);
      }
    } catch (error) {
      console.error("保存遥测数据时出错:", error);
      ElMessage.error("遥测数据保存失败");
    }
  }
};

// 停止视频采集 - 修复不自动保存问题
const stopVideoCollection = async () => {
  try {
    // 先记录当前计时器的时间作为实际采集时长，避免包含停止命令的处理时间
    actualCollectionDuration.value = collectionSeconds.value;
    actualCollectionEndTime.value = new Date();

    const result = await window.electronAPI.stopVideoCollection({
      endTime: actualCollectionEndTime.value.toISOString(),
      actualDuration: actualCollectionDuration.value,
    });

    isCollecting.value = false;

    // 停止遥测数据采集，但不保存（等用户确认）
    if (telemetryCollectionInterval.value) {
      clearInterval(telemetryCollectionInterval.value);
      telemetryCollectionInterval.value = null;
      console.log("遥测数据采集已停止，等待用户确认是否保存");
    }

    if (result.success) {
      ElMessage.success(
        `视频采集已停止，实际采集时长: ${formatTime(
          actualCollectionDuration.value
        )}`
      );
    } else {
      ElMessage.error(`停止采集失败: ${result.error}`);
    }
  } catch (error) {
    console.error("停止视频采集失败:", error);
    ElMessage.error("停止视频采集失败");
    isCollecting.value = false;

    // 停止遥测数据采集
    if (telemetryCollectionInterval.value) {
      clearInterval(telemetryCollectionInterval.value);
      telemetryCollectionInterval.value = null;
    }
  }
};

// 合并的采集切换方法
const toggleCollection = async () => {
  if (collectionStatus.value === "采集中") {
    await stopCollection();
  } else {
    await startCollection();
  }
};

// 开始采集
const startCollection = async () => {
  // 首先检测 FFmpeg 是否可用
  const ffmpegAvailable = await checkFFmpegAvailability();
  
  if (!ffmpegAvailable) {
    ElMessage.error("FFmpeg 不可用，无法开始视频采集");
    return;
  }
  
  // FFmpeg 检测通过，开始视频采集
  await startVideoCollection();
};

// 停止采集 - 修复逻辑
const stopCollection = async () => {
  try {
    collectionStatus.value = "待机";

    // 添加全局loading
    const loadingInstance = ElLoading.service({
      lock: true,
      text: "正在停止采集进程...",
      background: "rgba(0, 0, 0, 0.7)",
    });

    if (isCollecting.value) {
      await stopVideoCollection();
    }

    stopCollectionTimer(); // 在stopVideoCollection后停止计时器

    // 重置采集时间显示
    collectionDuration.value = "00:00:00";
    collectionSeconds.value = 0;

    // 关闭loading
    loadingInstance.close();

    // 只有在有采集数据时才显示保存确认对话框
    if (collectionTimestamp.value && actualCollectionDuration.value > 0) {
      showConfirmDialog.value = true;
    } else {
      ElMessage.warning("采集已停止，无采集数据");
      // 直接重置状态
      collectionTimestamp.value = "";
      actualCollectionStartTime.value = null;
      actualCollectionEndTime.value = null;
      actualCollectionDuration.value = 0;
    }
  } catch (error) {
    console.error("停止采集失败:", error);
    ElMessage.error("停止采集失败");
  }
};

// 视频卡片交互
const maximizeVideo = (i) => {
  const video = filteredVideoList.value[i];
  
  // 如果视频流已停用，提示用户
  if (!video.isEnabled) {
    ElMessage.warning(`${video.name} 已停用，无法进行放大操作`);
    return;
  }
  
  // 如果视频流离线，不允许放大
  if (video.status === 'offline') {
    ElMessage.warning(`${video.name} 当前离线，无法进行放大操作`);
    return;
  }
  
  // 调用对应视频组件的全屏方法
  const videoRef = videoRefs.value.get(video.id);
  if (videoRef && typeof videoRef.toggleFullscreen === 'function') {
    videoRef.toggleFullscreen();
  } else {
    console.warn('视频组件未找到或没有全屏方法');
  }
};

// 检查视频是否处于全屏状态
const isVideoFullscreen = (i) => {
  const video = filteredVideoList.value[i];
  
  // 优先使用我们跟踪的状态
  if (fullscreenStates.value.has(video.id)) {
    const isFullscreen = fullscreenStates.value.get(video.id);

    return isFullscreen;
  }
  
  // 备用方案：从组件引用获取状态
  const videoRef = videoRefs.value.get(video.id);
  if (videoRef && typeof videoRef.isFullscreen !== 'undefined') {
    const isFullscreen = videoRef.isFullscreen;
    return isFullscreen;
  }
  
  return false;
};

// 获取全屏按钮的工具提示文本
const getFullscreenTooltip = (i) => {
  if (isVideoFullscreen(i)) {
    return '退出全屏';
  }
  return '最大化';
};

const refreshGrid = () => {
  // 只改变布局，不刷新视频流
  console.log('布局已更改为每行', windowLayout.value, '路');
  // 布局变化会自动通过 gridStyle 计算属性更新
};

// 优化切换采集状态
const toggleCollect = async (i) => {
  // 采集中时禁止操作
  if (collectionStatus.value === "采集中") {
    ElMessage.warning("采集进行中，无法修改采集状态");
    return;
  }

  const video = filteredVideoList.value[i];

  // 如果视频流已停用，提示用户
  if (!video.isEnabled) {
    ElMessage.warning(`${video.name} 已停用，无法进行采集操作`);
    return;
  }
  
  // 如果视频流离线，不允许采集
  if (video.status === 'offline') {
    ElMessage.warning(`${video.name} 当前离线，无法进行采集操作`);
    return;
  }

  video.collecting = !video.collecting;

  // 记录操作并保存配置
  if (video.collecting) {
    video.collectStartTime = new Date();
    ElMessage.success(`${video.name} 已加入采集`);
  } else {
    video.collectStartTime = null;
    ElMessage.success(`${video.name} 已取消采集`);
  }

  // 保存配置到后端
  await saveVideoSourceConfig(video);
};















// 修复确认保存方法 - 只有用户确认时才保存
const confirmSave = async () => {
  console.log("=== 用户确认保存 ===");
  console.log("采集时间戳:", collectionTimestamp.value);
  console.log("实际采集时长:", actualCollectionDuration.value);
  
  showConfirmDialog.value = false;

  // 检查是否有采集时间戳
  if (!collectionTimestamp.value) {
    console.error("错误: 未找到采集时间戳");
    ElMessage.warning("未找到采集会话，无法保存文件");
    return;
  }

  try {
    // 添加保存loading
    const loadingInstance = ElLoading.service({
      lock: true,
      text: "正在保存采集文件...",
      background: "rgba(0, 0, 0, 0.7)",
    });

    // 无论是否还在采集中，都先确保采集进程已停止
    if (isCollecting.value) {
      console.log("检测到正在采集中，先停止采集进程...");
      ElMessage.info("正在停止采集进程...");
      await stopVideoCollection();
    }

    // 用户确认保存，现在保存遥测数据
    console.log("用户确认保存，开始保存遥测数据...");
    await stopTelemetryDataCollection();

    // 等待文件写入完成后保存
    console.log("等待文件写入完成...");
    setTimeout(() => {
      finalizeCollection(loadingInstance);
    }, 2000);
    
  } catch (error) {
    console.error("确认保存失败:", error);
    ElMessage.error("保存操作失败: " + error.message);
  }
};

// 用户取消保存 - 清理临时文件和数据
const cancelSave = async () => {
  console.log("=== 用户取消保存 ===");
  showConfirmDialog.value = false;
  
  // 停止遥测数据采集（如果还在进行）
  if (telemetryCollectionInterval.value) {
    clearInterval(telemetryCollectionInterval.value);
    telemetryCollectionInterval.value = null;
    console.log("遥测数据采集已停止");
  }
  
  // 清空遥测数据
  telemetryData.value = [];
  console.log("遥测数据已清空");
  
  // 删除采集时生成的文件夹和文件
  if (collectionTimestamp.value) {
    try {
      const outputDir = `./collections/${collectionTimestamp.value}`;
      console.log("正在删除采集文件夹:", outputDir);
      
      // 调用electron API删除文件夹
      if (window.electronAPI && window.electronAPI.executeCommand) {
        const result = await window.electronAPI.executeCommand("rm", ["-rf", outputDir]);
        if (result.success) {
          console.log("采集文件夹删除成功");
          ElMessage.success("已取消保存并删除采集文件");
        } else {
          console.error("删除文件夹失败:", result.stderr);
          ElMessage.warning("已取消保存，但删除文件时出现问题");
        }
      } else {
        ElMessage.info("已取消保存（模拟环境）");
      }
    } catch (error) {
      console.error("删除采集文件夹时出错:", error);
      ElMessage.warning("已取消保存，但删除文件时出现问题");
    }
  }
  
  // 重置采集状态
  collectionTimestamp.value = "";
  actualCollectionStartTime.value = null;
  actualCollectionEndTime.value = null;
  actualCollectionDuration.value = 0;
  
  console.log("采集状态已重置，所有临时数据已清理");
};

// 处理视频播放器错误
const handleVideoError = (error) => {
  console.error(`视频播放器错误:`, error);
  
  // 查找对应的视频索引 - 通过错误信息中的URL来匹配
  const videoIndex = videoList.value.findIndex(video => 
    video.src === error.url || video.streamUrl === error.url
  );
  
  if (videoIndex !== -1 && videoList.value[videoIndex]) {
    const video = videoList.value[videoIndex];
    
    // 只对启用的视频流处理错误
    if (video.isEnabled) {
      // 连接失败，设置为离线状态
      video.status = 'offline';
      // 使用友好的错误信息，避免显示技术性代码
      const friendlyError = error.detail && typeof error.detail === 'string' && !error.detail.includes('[object') 
        ? error.detail 
        : '视频流连接异常';
      video.errorMessage = friendlyError;
    }
  } else {
    // 如果找不到匹配的视频，显示通用错误
    console.warn('无法找到对应的视频索引，显示通用错误');
  }
  
  // 不显示弹窗错误提示，只在控制台记录
  console.warn('视频播放错误，已记录错误信息');
};

// 处理视频重连失败
const handleVideoReconnectFailed = (data) => {
  console.error(`视频重连失败:`, data);
  console.log('handleVideoReconnectFailed函数被调用，接收到的数据:', data);
  
  // 查找对应的视频索引 - 通过重连失败信息中的URL来匹配
  console.log('查找视频索引，接收到的URL:', data.url);
  console.log('当前视频列表:', videoList.value.map(v => ({ id: v.id, src: v.src, streamUrl: v.streamUrl })));
  
  const videoIndex = videoList.value.findIndex(video => 
    video.src === data.url || video.streamUrl === data.url
  );
  
  console.log('找到的视频索引:', videoIndex);
  
  if (videoIndex !== -1 && videoList.value[videoIndex]) {
    const video = videoList.value[videoIndex];
    
    // 只对启用的视频流处理重连失败
    if (video.isEnabled) {
      // 重连失败，设置为离线状态
      video.status = 'offline';
      video.errorMessage = `网络连接异常，已尝试重连${data.attempts}次`;
      console.log(`视频 ${videoIndex} 重连失败${data.attempts}次，已设置为离线状态`);
    }
  } else {
    console.warn('无法找到对应的视频索引，显示通用错误');
  }
  
  // 不显示弹窗错误提示，只在控制台记录
  console.warn('视频重连失败，已记录错误信息');
};

// 处理视频连接成功
const handleVideoConnected = (data) => {
  console.log(`视频连接成功:`, data);
  
  // 查找对应的视频索引 - 通过连接信息中的URL来匹配
  const videoIndex = videoList.value.findIndex(video => 
    video.src === data.url || video.streamUrl === data.url
  );
  
  if (videoIndex !== -1 && videoList.value[videoIndex]) {
    const video = videoList.value[videoIndex];
    
    // 只对启用的视频流处理连接成功
    if (video.isEnabled) {
      video.status = 'online';
      video.errorMessage = '';
      console.log(`视频 ${videoIndex} 连接成功，耗时: ${data.time}ms`);
    }
  } else {
    console.warn('无法找到对应的视频索引');
  }
};

// 处理播放模式变化
const handleModeChange = (newMode, videoIndex) => {
  console.log(`视频 ${videoIndex} 播放模式切换为: ${newMode}`);
  
  // 可以在这里添加模式变化的处理逻辑
  // 例如：记录用户偏好、更新配置等
};

// 处理视频状态变化
const handleVideoStatusChange = (status, videoIndex) => {
  console.log(`视频 ${videoIndex} 状态变化为: ${status}`);
  
  // 更新视频状态
  if (videoList.value[videoIndex]) {
    const video = videoList.value[videoIndex];
    
    switch (status) {
      case 'connected':
        video.status = 'online';
        video.errorMessage = '';
        break;
      case 'connecting':
        video.status = 'online';
        video.errorMessage = '连接中...';
        break;
      case 'error':
        video.status = 'offline';
        video.errorMessage = '连接失败';
        break;
      case 'disconnected':
        video.status = 'offline';
        video.errorMessage = '连接断开';
        break;
    }
  }
};

// 处理全屏状态变化
const handleFullscreenChange = (isFullscreen, videoId) => {
  console.log(`视频 ${videoId} 全屏状态变化:`, isFullscreen);
  
  // 更新全屏状态跟踪
  fullscreenStates.value.set(videoId, isFullscreen);
  
  // 强制更新组件，确保UI响应状态变化
  // 使用nextTick确保DOM更新
  import('vue').then(({ nextTick }) => {
    nextTick(() => {
      // 强制触发响应式更新
      videoList.value = [...videoList.value];
      console.log('强制更新完成');
    });
  });
};

// 直接完成采集保存 - 添加API调用
const finalizeCollection = async (loadingInstance) => {
  try {
    console.log("=== 开始文件整理 ===");
    
    const collectingChannels = videoList.value.filter(
      (v) => v.collecting && v.isEnabled && v.status === 'online'
    );

    console.log("需要保存的采集通道:", collectingChannels.map(c => ({ id: c.id, name: c.name })));

    if (collectingChannels.length === 0) {
      console.warn("警告: 没有找到需要保存的采集文件");
      loadingInstance.close();
      ElMessage.warning("没有找到需要保存的采集文件");
      return;
    }

    if (!collectionTimestamp.value) {
      console.error("错误: 未找到采集会话时间戳");
      loadingInstance.close();
      ElMessage.warning("未找到采集会话，无法保存文件");
      return;
    }

    // 本地保存路径
    const outputDir = `./collections/${collectionTimestamp.value}`;
    
    console.log("检查采集文件夹是否存在:", outputDir);
    
    // 调用视频数据API保存到后端
    try {
      console.log("=== 调用视频数据API ===");
      
      // 导入视频数据API
      const { videoDataAPI } = await import('../api/index.js');
      
      // 准备API参数
      const videoDataParams = {
        startCollectTime: actualCollectionStartTime.value 
          ? formatLocalDateTime(actualCollectionStartTime.value)
          : formatLocalDateTime(new Date()),
        endCollectTime: actualCollectionEndTime.value 
          ? formatLocalDateTime(actualCollectionEndTime.value)
          : formatLocalDateTime(new Date()),
        storagePath: outputDir,
        remark: `采集了 ${collectingChannels.length} 路视频流，时长: ${formatTime(actualCollectionDuration.value)}`
      };
      
      console.log("视频数据API参数:", videoDataParams);
      
      // 调用API
      const apiResponse = await videoDataAPI.addVideoData(videoDataParams);
      
      if (apiResponse && apiResponse.code == 0) {
        console.log("✓ 视频数据已保存到后端");
        ElMessage.success("采集数据已保存到后端");
      } else {
        console.warn("⚠ API保存失败，但本地文件已保存:", apiResponse?.msg);
        ElMessage.warning("本地文件已保存，但后端保存失败");
      }
      
    } catch (apiError) {
      console.error("API调用失败:", apiError);
      ElMessage.warning("本地文件已保存，但后端保存失败");
    }
    
    loadingInstance.close();
    
    ElMessage.success(
      `文件保存完成！采集时长: ${formatTime(actualCollectionDuration.value)}，保存路径: ${outputDir}`
    );
    
    console.log("✓ 文件保存完成");

    // 重置所有采集相关状态
    console.log("重置采集状态");
    collectionTimestamp.value = "";
    actualCollectionStartTime.value = null;
    actualCollectionEndTime.value = null;
    actualCollectionDuration.value = 0;
    
    console.log("=== 保存流程完成 ===");
  } catch (error) {
    console.error("✗ 文件整理过程中发生错误:", error);
    loadingInstance.close();
    ElMessage.error("保存操作失败: " + error.message);
  }
};

onMounted(async () => {
  updateTime();
  timer = setInterval(updateTime, 1000);
  
  // 初始化时加载视频流列表
  await loadVideoStreamList();
});

onUnmounted(() => {
  if (timer) clearInterval(timer);
  if (collectionTimer.value) clearInterval(collectionTimer.value);
});
</script>

<style scoped>
.data-collection {
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 16px;
  gap: 8px;
  overflow: hidden;
}
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 12px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  flex-shrink: 0;
}
.status-left {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
}
.status-right {
  display: flex;
  gap: 8px;
}
.video-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}
.toolbar-left {
  display: flex;
  align-items: center;
  gap: 8px;
}
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
}
.toolbar-label {
  font-size: 14px;
  color: #333;
  margin-right: 4px;
}
.video-scroll-wrapper {
  max-height: 500px;
  min-height: 180px;
  height: auto;
  overflow-y: auto;
  background: transparent;
  border-radius: 8px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.loading-state p {
  margin-top: 16px;
  color: #666;
  font-size: 14px;
}
.video-grid {
  width: 100%;
  margin: 0 auto;
  min-height: 200px;
  display: grid;
  gap: 16px;
}

.video-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  min-height: 180px;
  aspect-ratio: 16/10;
  width: 100%;
}

.video-card.disabled {
  background: linear-gradient(135deg, #f9fafb 0%, #f3f4f6 100%);
  border: 2px solid #e5e7eb;
  box-shadow: 0 4px 12px rgba(156, 163, 175, 0.15);
  position: relative;
  opacity: 0.7;
}

.video-card.disabled::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #9ca3af, #6b7280);
  border-radius: 8px 8px 0 0;
}



.video-card-topbar {
  position: absolute;
  top: 8px;
  left: 8px;
  z-index: 1;
  display: flex;
  align-items: center;
  gap: 8px;
  pointer-events: none;
}
.video-title {
  font-size: 14px;
  font-weight: 600;
  color: #fff;
  background: rgba(0, 0, 0, 0.45);
  border-radius: 4px;
  padding: 2px 8px;
  pointer-events: auto;
}
.video-status-text {
  font-weight: bold;
  margin-left: 8px;
  font-size: 15px;
  letter-spacing: 1px;
}
.video-status-text.online {
  color: #21c521;
  text-shadow: 0 0 2px #0a7a0a;
}
.video-status-text.offline {
  color: #ff3b3b;
  text-shadow: 0 0 2px #a10000;
}
.video-status-text.connecting {
  color: #f59e0b;
  text-shadow: 0 0 2px #d97706;
  animation: pulse 1.5s ease-in-out infinite;
}

.video-status-text.online {
  color: #21c521;
  text-shadow: 0 0 2px #0a7a0a;
}

.video-status-text.offline {
  color: #ff3b3b;
  text-shadow: 0 0 2px #a10000;
}

.video-status-text.disabled {
  color: #9ca3af;
  text-shadow: 0 0 2px #6b7280;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.6; }
}

.video-card-icons {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 3;
  display: flex;
  gap: 8px;
  pointer-events: auto;
}
.video-icon {
  color: #fff;
  font-size: 22px;
  cursor: pointer;
  transition: color 0.2s, transform 0.2s;
  opacity: 0.85;
}
.video-icon:hover {
  color: #ffd700;
  opacity: 1;
  transform: scale(1.18);
}
.video-icon.disabled {
  opacity: 0.3;
  cursor: not-allowed;
  pointer-events: none;
}

.video-icon.disabled:hover {
  color: #fff;
  opacity: 0.3;
  transform: none;
}

.video-icon.fullscreen {
  color: #ffd700 !important;
  opacity: 1;
  transform: scale(1.1);
}

.video-icon.fullscreen:hover {
  color: #ffed4e !important;
  transform: scale(1.2);
}

.video-card-body {
  flex: 1 1 0;
  display: flex;
  align-items: stretch;
  justify-content: stretch;
  padding: 0;
  height: 100%;
}
.video-placeholder {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #666;
  font-size: 16px;
  text-align: center;
  padding: 20px;
  height: 100%;
}

.video-placeholder.disabled {
  padding: 15px 10px;
}

.disabled-content {
  max-width: 200px;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.disabled-title {
  color: #6b7280;
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px 0;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.disabled-message {
  color: #9ca3af;
  font-size: 12px;
  margin: 0 0 12px 0;
  line-height: 1.3;
  background: rgba(156, 163, 175, 0.1);
  padding: 6px 8px;
  border-radius: 4px;
  border-left: 2px solid #9ca3af;
  text-align: center;
  max-height: 3em;
  overflow: hidden;
  text-overflow: ellipsis;
}




.video-player {
  width: 100% !important;
  height: 100% !important;
}
.video-container,
.video-container video {
  width: 100% !important;
  height: 100% !important;
  object-fit: cover !important;
}
.chart-section {
  background: white;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  height: 280px;
  flex-shrink: 0;
}
@media (max-width: 1200px) {
  .video-grid {
    grid-template-columns: repeat(2, 1fr) !important;
  }
}
@media (max-width: 768px) {
  .data-collection {
    padding: 12px;
    gap: 12px;
  }
  .video-grid {
    grid-template-columns: 1fr !important;
  }
  .status-left {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
  }
}
</style>
